package com.xs.gis.cover.util;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xs.gis.cover.coverImpl.GeoJsonCover;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.Driver;
import org.gdal.gdal.gdal;
import org.gdal.gdalconst.gdalconstConstants;
import org.gdal.ogr.*;
import org.gdal.osr.SpatialReference;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.processing.Operations;
import org.geotools.gce.geotiff.GeoTiffReader;
import org.geotools.gce.geotiff.GeoTiffWriter;
import org.locationtech.jts.geom.Geometry;
import org.opengis.coverage.grid.GridCoverage;

import java.io.File;

/**
 * @description:
 * @author: bo
 * @create: 2025-07-02 10:27
 */
@Slf4j
public class TifUtils {

    static {
        // 初始化 GDAL 和 OGR

        // System.setProperty("java.library.path", "C:\\Program Files\\GDAL\\gdalalljni.dll");

        // System.load(System.getProperty("user.dir")+"/src/main/resources/gdalalljni.dll");
        // 注册所有的驱动
        gdal.AllRegister();
        // 为了支持中文路径，请添加下面这句代码
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
        // 为了使属性表字段支持中文，请添加下面这句
        gdal.SetConfigOption("SHAPE_ENCODING", "CP936");

        ogr.RegisterAll();
    }
    public static String clip(String geojsonStr,String originalFilePath) throws Exception {
        try {

            String clippingParentDirFileStr = FilenameUtils.getPath(originalFilePath);
            String outputFilePath = clippingParentDirFileStr+ File.separator+String.valueOf(RandomUtils.nextInt())+".tif";

            JSONObject jsonObject = JSONUtil.parseObj(geojsonStr);
            String features = jsonObject.getStr("features");
            // GeoJSON 边界
            Object geojson =  JSONUtil.parseArray(features).getJSONObject(0).get("geometry");
            String geo2 = JSONUtil.toJsonStr(geojson);
            GeoJsonCover geoJsonCover = CoverFactory.buildGeoJsonCover();

            Geometry polygon = geoJsonCover.dataToGeometry(geo2);
            // 读取.tif文件
            GeoTiffReader reader = new GeoTiffReader(new File(originalFilePath));
            GridCoverage2D coverage = reader.read(null);
            polygon.setSRID(4326);
            GridCoverage crop = (GridCoverage) Operations.DEFAULT.crop(coverage, polygon);

            // 写出裁剪后的.tif文件
            GeoTiffWriter writer = new GeoTiffWriter(new File(outputFilePath));
            writer.write(crop, null);
            writer.dispose();
            return outputFilePath;
        }
        catch (Exception e){
            log.error(e.getMessage());
            return null;
        }
    }


    // public static String clip(String geojsonStr,String originalFilePath) throws Exception {
    //     try {
    //         log.info("开始文件裁剪");
    //         // 输入和输出文件路径
    //         String inputFilePath = originalFilePath;
    //         String clippingParentDirFileStr = FileUtil.getParent(originalFilePath, 1);
    //         String uuid = UUID.fastUUID().toString();
    //         String outputFilePath = clippingParentDirFileStr+ File.separator+uuid+".tif";
    //
    //         JSONObject jsonObject = JSONUtil.parseObj(geojsonStr);
    //         String features = jsonObject.getStr("features");
    //         // GeoJSON 边界
    //         Object geojson =  JSONArray.parseArray(features).getJSONObject(0).get("geometry");
    //         String geo2 = JsonUtils.objectToJson(geojson);
    //
    //         // 读取输入 TIFF 文件
    //         Dataset inputDataset = gdal.Open(inputFilePath, gdalconstConstants.GA_ReadOnly);
    //         if (inputDataset == null) {
    //             log.error("Failed to open input file: " + inputFilePath);
    //             return null;
    //         }
    //         //geo2  = "{\"type\":\"Polygon\",\"coordinates\":[[[103.79572373948669,36.03984208324239],[103.93959004504224,36.03984208324239],[103.93959004504224,36.14632580546461],[103.79572373948669,36.14632580546461],[103.79572373948669,36.03984208324239]]]}";
    //         // 解析 GeoJSON 边界
    //         org.gdal.ogr.Geometry geometry = org.gdal.ogr.Geometry.CreateFromJson(geo2);
    //
    //
    //
    //         if (geometry == null) {
    //             log.error("Failed to parse GeoJSON: " + geo2);
    //             return null;
    //         }
    //
    //         // 获取输入数据集的坐标参考系统
    //         SpatialReference sr = new SpatialReference();
    //         sr.ImportFromWkt(inputDataset.GetProjectionRef());
    //
    //         // 将几何体转换到输入数据集的坐标系
    //         geometry.AssignSpatialReference(sr);
    //
    //         // 创建临时的内存数据源来存储裁剪边界
    //         DataSource ds = ogr.GetDriverByName("Memory").CreateDataSource("memData");
    //
    //         Layer layer = ds.CreateLayer("clip", sr, ogr.wkbPolygon);
    //         FieldDefn fieldDefn = new FieldDefn("id", ogr.OFTInteger);
    //         layer.CreateField(fieldDefn);
    //
    //         // 创建特征
    //         Feature feature = new Feature(layer.GetLayerDefn());
    //         feature.SetGeometry(geometry);
    //         feature.SetField("id", 1);
    //         layer.CreateFeature(feature);
    //
    //         // 裁剪 TIFF 文件
    //         Driver driver = gdal.GetDriverByName("GTiff");
    //         Dataset outputDataset = driver.CreateCopy(outputFilePath, inputDataset, 0, new String[]{
    //                 "-cutline", "memData",
    //                 "-crop_to_cutline",
    //                 "-of", "GTiff"
    //         });
    //
    //         if (outputDataset == null) {
    //             log.error("Failed to create output file: " + outputFilePath);
    //             return null;
    //         }
    //
    //         // 清理资源
    //         outputDataset.delete();
    //         inputDataset.delete();
    //         ds.delete();
    //         geometry.delete();
    //         sr.delete();
    //
    //         log.info("裁剪完成！");
    //         return outputFilePath;
    //     }
    //     catch (Exception e){
    //         log.error(e.getMessage());
    //         return null;
    //     }
    // }

    public static void main(String[] args)  throws Exception{
        String zone = "{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[87.46626839028467,43.94776753752734],[87.49124512063135,43.94776753752734],[87.49124512063135,43.97102908718526],[87.46626839028467,43.97102908718526],[87.46626839028467,43.94776753752734]]]},\"properties\":{\"name\":\"task\"}}],\"crs\":{\"type\":\"name\",\"properties\":{\"name\":\"EPSG:4326\"}}}";
        String path = "D:\\work-files\\耕地变化图斑.tif";
        clip(zone,path);
    }

}
